<template>
  <view class="editable-card" :class="{ editing: isEditing }" @click="handleClick">
    <view class="checkbox-container" v-if="hasCheckbox">
      <checkbox-group @change="onChecked">
        <label>
          <checkbox :value="true" :checked="internalChecked" />
        </label>
      </checkbox-group>
    </view>
    <view class="inner-container">
      <view class="content-container">
        <slot></slot>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { isArray } from 'wot-design-uni/components/common/util'

interface Props {
  modelValue?: boolean
  checked?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  checked: false,
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'checkChange', value: boolean): void
  (e: 'click'): void
}>()

const isEditing = ref(props.modelValue)
const internalChecked = ref(props.checked)

const hasCheckbox = ref(props.checked !== undefined)

watch(
  () => props.modelValue,
  (newValue) => {
    isEditing.value = newValue
  },
)

watch(
  () => props.checked,
  (newValue) => {
    if (newValue !== undefined) {
      internalChecked.value = newValue
      hasCheckbox.value = true
    } else {
      hasCheckbox.value = false
    }
  },
)

const handleClick = () => {
  if (isEditing.value && hasCheckbox.value) {
    internalChecked.value = !internalChecked.value
    emit('checkChange', internalChecked.value)
  } else if (!isEditing.value) {
    emit('click')
  }
}
const onChecked = (e: any) => {
  let check = false
  if (isArray(e.detail.value) && e.detail.value.length) {
    check = true
  }
  internalChecked.value = check
  emit('checkChange', internalChecked.value)
}
</script>

<style scoped lang="scss">
.editable-card {
  position: relative;
  overflow: hidden;
  .inner-container {
    display: flex;
    transition: transform 0.5s ease-in-out;
  }
  .radio-img {
    width: 30px;
  }
  .checkbox-container {
    position: absolute;
    left: -80px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 100%;
    transition: left 0.5s ease-in-out;
  }

  .content-container {
    flex: 1;
    min-width: 0;
  }

  &.editing {
    .inner-container {
      transform: translateX(80px);
    }
    .checkbox-container {
      left: 0;
    }
  }
}
</style>
